<script setup lang="ts">
import { computed, type PropType, provide, ref, watch } from "vue";
import type { SimpleNavigationCustomHooks } from "./simple-navigation-helper";

defineOptions({ name: "simple-navigation-item" });

const props = defineProps({
  visible: { type: Boolean },
  args: { type: [Object, Array, Number, Boolean, String] as PropType<any> },
});

const hooks = {
  onFocus: [] as Function[],
  onBlur: [] as Function[],
};

provide("simple-navigation-item-custom-hooks", <SimpleNavigationCustomHooks>{
  onFocus: (fn: Function) => hooks.onFocus.push(fn),
  removeFocusHandler: (fn: Function) => {
    const index = hooks.onFocus.indexOf(fn);
    if (index !== -1) {
      hooks.onFocus.splice(index, 1);
    }
  },
  onBlur: (fn: Function) => hooks.onBlur.push(fn),
  removeBlurHandler: (fn: Function) => {
    const index = hooks.onBlur.indexOf(fn);
    if (index !== -1) {
      hooks.onBlur.splice(index, 1);
    }
  },
});

const isVisible = ref(props.visible);
provide("simple-navigation-item-visible", isVisible);

watch(
  () => props.visible,
  visible => {
    isVisible.value = visible;
    if (visible) {
      hooks.onFocus.forEach(fn => fn());
    } else {
      hooks.onBlur.forEach(fn => fn());
    }
  },
);

const navigationArgs = computed(() => props.args);
provide("simple-navigation-item-args", navigationArgs);
</script>

<template>
  <slot />
</template>
